package edu.gatech.oad.cyberdoc.view.report;

import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

public class GoogleWeightChart {

	/**
	 * The logger for this class.
	 */
	private static final Logger LOG;

	static {
		LOG = Logger.getLogger("edu.gatech.oad.cyberdoc.view."
				+ "GoogleWeightChart");
	}
	
	private static final String URL = "http://chart.apis.google.com/chart"
			+ "?chxr=0,%miny%,%maxy%&chxs=0,676767,11.5,0,lt,676767&chxt=y"
			+ "&chs=440x220&cht=lxy&chco=3072F3&chd=t:-1|%y%&chdlp=b&chls=3"
			+ "&chma=5,5,5,25&chtt=Weight";

	private static final int MIN_Y = 100;
	private static final int MAX_Y = 250;

	public Image getWeightChart(int[] weights) {
		int[] y = new int[weights.length];

		for (int i = 0; i < y.length; i++) {
			y[i] = 100 * (weights[i] - MIN_Y) / MAX_Y;
		}

		String url = URL.replace("%maxy%", "" + MAX_Y);
		url = url.replace("%miny%", "" + MIN_Y);
		url = url.replace("%y%", implode(y));

		Image image = null;
		
		try {
			image = ImageIO.read(new URL(url));
		} catch (MalformedURLException e) {
			LOG.log(Level.SEVERE, "Unexpected exception", e);
		} catch (IOException e) {
			LOG.log(Level.SEVERE, "Unexpected exception", e);
		}
		
		return image;
	}

	private static String implode(int[] array) {
		StringBuffer buffer = new StringBuffer(array.length * 2);

		for (int i : array) {
			buffer.append(i);
			buffer.append(',');
		}

		if (buffer.length() > 0) {
			buffer = buffer.delete(buffer.length() - 1, buffer.length());
		}
		
		return buffer.toString();
	}
}
